package chances.epg.session;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.FrameworkServlet;

public class UserSessionListener implements HttpSessionAttributeListener {

	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		String name = event.getName();
		if (UserSession.USER_SESSION_NAME.equals(name)) {
			UserSessionService userSessionService = getUserSessionService(event);
			UserSession userSession = (UserSession) event.getValue();
			if (!userSessionService.exist(userSession.getUserId())) {
				userSessionService.add(userSession);
			}
		}
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		String name = event.getName();
		if (UserSession.USER_SESSION_NAME.equals(name)) {
			UserSession userSession = (UserSession) event.getValue();
			UserSessionService userSessionService = getUserSessionService(event);
			userSessionService.remove(userSession.getUserId());
		}
	}

	private UserSessionService getUserSessionService(HttpSessionBindingEvent event) {
		String key =FrameworkServlet.SERVLET_CONTEXT_PREFIX +"epg";
		ApplicationContext applicationContext = (ApplicationContext) event.getSession().getServletContext().getAttribute(key);
		return applicationContext.getBean(UserSessionService.class);
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent arg0) {
		attributeAdded(arg0);
	}

}
